Vue.component("yl-upload", {
  template: `<div>
    <div class="preview" v-if="Picture_URL">
        <el-image ref="FImage" class="el-upload-list__item-thumbnail" style="width: 148px; height: 148px" :preview-src-list="[base64?Picture_URL:base + Picture_URL]" :src="base64?Picture_URL:base + Picture_URL" fit="contain"></el-image>
        <span class="el-upload-list__item-actions">
            <span @click="handlePictureCardPreview('FImage')"><i class="el-icon-zoom-in"></i></span>
            <span @click="handleRemove"><i class="el-icon-delete"></i></span>
        </span>
    </div>
    <el-upload :disabled="loading" v-else class="upload-demo" :show-file-list="false" :on-change="upload"
        list-type="picture-card" action="" accept="image/*" :auto-upload="false">
        <i slot="default" :class="loading?'el-icon-loading':'el-icon-plus'"></i>
        <div v-if="!unslider" class="el-upload__tip" slot="tip">
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
            <el-slider :min="1" style="width:148px" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" fit="contain" :src="dialogImageUrl">
    </el-dialog></div>`,
  props: {
    value: {
      type: String,
      default: "",
    },
    base: {
      type: String,
      default: "",
    },
    base64: {
      type: Boolean,
      default: false,
    },
    unslider: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      Picture_URL: this.value,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      quality: 100,
    };
  },
  watch: {
    value(newVal) {
      this.Picture_URL = newVal;
    },
    Picture_URL(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    formatTooltip(val) {
      return "图片压缩比例：" + val + "%";
    },
    upload({ raw }) {
      const that = this;
      new Compressor(raw, {
        quality: that.quality / 100,
        success(file) {
          that.loading = true;
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            if (!that.base64) {
              $.ajax({
                type: "POST",
                // utils.js和文件中接口名/有冲突 检查保留哪一个
                url: DomainName1 + "BusinessPIC",
                data: {
                  Data: e.target.result,
                  DataLength: file.size,
                  FileName: file.name,
                  logo: true,
                },
                complete: function (XMLHttpRequest) {
                  that.loading = false;
                  if (
                    XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT"
                  ) {
                    window.parent.document.location.href =
                      absolutepath() +
                      XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                success: function (Result) {
                  if (Result.Status == "success") {
                    that.Picture_URL = Result.Picture_Url;
                    that.$message.success("上传成功");
                  } else {
                    that.$message.error("上传失败");
                  }
                },
                error: function () {
                  that.$message.error("操作失败，请稍后再试");
                },
                dataType: "json",
              });
            } else {
              that.Picture_URL = e.target.result;
              that.loading = false;
            }
          };
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    handlePictureCardPreview(formName) {
      this.$refs[formName].showViewer = true;
    },
    handleRemove() {
      this.Picture_URL = "";
      this.$emit("remove");
    },
  },
});
new Vue({
  el: "#app",
  data() {
    const validator = (rule, value, callback) => {
      if (value == "<p><br></p>") {
        callback(new Error('请输入内容'));
      } else {
        callback();
      }
    }
    return {
      props: {
        templateString: "<div>{{ message }}</div>", // 默认模板
        message: "Hello, Vue 2!",
        multiple: true,
        label: "New_Type_Name",
        value: "New_Type_SerialNumber",
      },
      options: [],
      fileList: [],
      News_Type: [
        {
          value: "0",
          label: "产业技术",
        },
        {
          value: "1",
          label: "文化宣传",
        },
        {
          value: "2",
          label: "产品展示",
        },
        {
          value: "3",
          label: "政策",
        },
        {
          value: "4",
          label: "法规",
        },
      ],
      rules: {
        News_Name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        News_Main: [{ required: true, validator: validator, trigger: 'blur' }],
      },
      type: [],
      form: {
        News_SerialNumber: "",
        News_Name: "",
        News_Type: getQueryObject().News_Type
          ? getQueryObject().News_Type
          : "0",
        News_Type_SerialNumber: "",
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        News_Date: "",
        News_Main: "",
        Picture_URL: "",
      },
      loading: false,
    };
  },
  mounted() {
    $("title").text(this.News_Label + "添加");
    let News_SerialNumber = window.sessionStorage.getItem("News_SerialNumber");
    // console.log(News_SerialNumber);

    this.getData(News_SerialNumber);
  },
  computed: {
    News_Label() {
      if (getQueryObject().News_Type) {
        this.form.News_Type = getQueryObject().News_Type;
      }
      let ObjNew_Type = this.News_Type.filter(
        (i) => i.value == this.form.News_Type
      )[0];
      return ObjNew_Type.label;
    },
  },
  methods: {
    getData(News_SerialNumber) {
      const that = this;
      $.ajax({
        url: `${BASE_URL1}/NewTypeAll`,
        type: "POST",
        data: {
          Data: JSON.stringify({
            Add: {
              news_info: [that.form],
            },
          }),
        },
        success: function (data) {
          that.options = data;
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalGetDataStructure`,
        type: "POST",
        data: {
          DocumentSerialNumber: News_SerialNumber,
          Data: JSON.stringify({ news_info: { news_detail: {} } }),
          Condition: "",
        },
        success: function ({ news_info }) {
          console.log("newsinfo", news_info);
          if (news_info.length == 1) {
            that.form = news_info[0];
            that.type = news_info[0].Detail_JSON;
            that.fileList = [
              {
                name: news_info[0].Picture_URL,
                url: "https://www.kdddy.cn/Image/" + news_info[0].Picture_URL,
              },
            ];
          }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    handleBeforeUpload(file) {
      // 生成预览URL并添加到fileList中
      const reader = new FileReader();
      reader.onload = (e) => {
        //调用存储的接口放在onload中，存在异步操作
        const newFile = {
          name: file.name,
          url: e.target.result, // 预览URL
          uid: file.uid, //添加uid
          // 可以添加其他属性，如上传状态等
        };
        this.fileList.push(newFile);
        // for (let i = 0; i < this.fileList.length; i++) {
        //   this.fileList[i].uid = "D_" + this.fileList[i].uid;
        // }
        console.log(this.fileList);

        // return;
        $.ajax({
          // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
          url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          type: "POST", // 注意HTTP方法应该大写
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          data: JSON.stringify(this.fileList), // 将数据序列化为JSON字符串
          success: function (Result) {
            console.log(Result);
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
          },
          dataType: "json", // 预期服务器返回的数据类型
        });
      };
      reader.readAsDataURL(file);
      // 返回false以阻止自动上传

      return false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let base64Image = this.fileList[0].url;
          let dataIndex = base64Image.indexOf("data:");
          let base64Index = base64Image.indexOf(";base64,");
          let substring = base64Image.substring(dataIndex + 5, base64Index);
          let ls_split = substring.split("/");
          this.form.Picture_URL = this.fileList[0].uid + "." + ls_split[1];

          console.log(this.form);
          let lArray = new Array();
          lArray.push(this.form);
          let lJSONObject_news_info = new Object();
          lJSONObject_news_info.news_info = lArray; //换表
          let lJSONObject_DataSet = new Object(); // Modify
          lJSONObject_DataSet.Modify = lJSONObject_news_info; //换表
          const _this = this;
          $.ajax({
            // headers: requestHeaders(),
            // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
            url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
            type: "POST",
            data: {
              Data: JSON.stringify(lJSONObject_DataSet),
            },
            success: function (Result) {
              console.log(Result);
              if (Result.Status === "success") {
                _this.$message({
                  message: "提交成功",
                  type: "success",
                });
                window.history.go(-1);
              } else {
                _this.$message.error("提交失败，请稍后再试");
              }
            },
            complete: function (XMLHttpRequest) {
              requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
            },
            dataType: "json",
          });
        }
      })

      return;
      const that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.loading = true;
          let base64Image = that.fileList[0].url;
          let dataIndex = base64Image.indexOf("data:");
          let base64Index = base64Image.indexOf(";base64,");
          let substring = base64Image.substring(dataIndex + 5, base64Index);
          let ls_split = substring.split("/");
          that.form.Picture_URL = that.fileList[0].uid + "." + ls_split[1];

          const { add, modify } = that.deal();
          let data = {};
          if (add == null) {
            data = {
              Data: JSON.stringify({ Modify: { news_info: [modify] } }),
            };
          } else {
            delete add.value1;
            data = {
              Data: JSON.stringify({
                Modify: { news_info: [modify] },
                Add: { news_info: [add] },
              }),
            };
          }
          $.ajax({
            headers: requestHeaders(),
            url: `${BASE_URL2}/generalBusiness/generalSave`,
            type: "POST",
            data,
            success: function (res) {
              if (res.Status === "success") {
                that.$message.success("修改成功");
                window.history.go(-1);
              } else {
                that.$message.error("提交失败，请稍后再试");
              }
            },
            error: function () {
              that.$message.error("操作失败，请稍后再试");
            },
            complete: function (XMLHttpRequest) {
              that.loading = false;
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        } else {
          that.$message({
            message: sumberError,
            type: "warning",
          });
          return false;
        }
      });
    },
    deal() {
      const add = deepClone(this.form);
      const modify = deepClone(this.form);
      let add_news_detail = [],
        modify_news_detail = [];
      for (const i in modify.Children.news_detail) {
        const obj = modify.Children.news_detail[i];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          add_news_detail.push(obj);
        } else {
          modify_news_detail.push(obj);
        }
      }
      add.Children.news_detail = add_news_detail;
      modify.Children.news_detail = modify_news_detail;
      if (add_news_detail.length == 0 && modify_news_detail.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
  },
});
